import { useNavigate, Outlet, useLocation } from "react-router-dom";
import { Menu, Breadcrumb } from "antd";
import './index.css';
import router from "../../routes/router";
import React, { useState, useEffect } from "react";


function Index() {
  const [current, setCurrent] = useState('/Index');
  const [dqly, setDqly] = useState([]);
  const [col, setCol] = useState(0);

  const location = useLocation();
  const navigate = useNavigate();





  const rts = router.map(e => ({
    label: <span style={{ display: 'inline-block', lineHeight: '45px' }} onClick={(event) => onClick(e.path, event, e.meta?.auth)}>{e.path}</span>,
    key: e.path,
    icon: e.icon,
    children: e.children ? e.children.map(v => ({
      label: v.name,
      key: e.path + '/' + v.path,
      icon: v.icon,
    })) : null
  }));
  rts.shift();

  useEffect(() => {
    setDqly(location.pathname.split('/'));
  }, [location.pathname]);

  const handleScroll = () => {
    setCol(window.scrollY);
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  function onClick(e, event, auth) {
    event?.stopPropagation();
    // console.log('click ', e);
    if (e.key) {
      setCurrent(e.key);
      navigate(e.key, { state: { a: 1 } });
    } else {
      setCurrent(`${e}?`);
      navigate(`${e}?`, { state: { a: 1 } });
    }
  }

  return (
    <div className="sumIndex">
      <Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={rts} />
      <Breadcrumb separator=">" items={dqly.map((segment, index) => ({
        title: segment,
        onClick: () => {
          navigate(`${dqly.slice(0, index + 1).join('/')}`)
          setCurrent(`${dqly.slice(0, index + 1).join('/')}`);
        },

      }))}

      />
      <div className="books">
        <div>aaa</div>
        <div>bbb</div>
        <div>ccc</div>
      </div>
      <Outlet />
      <div type="primary" style={{ display: col > 250 ? 'block' : 'none' }} className="toTop" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
        返回顶部
      </div>
    </div>
  );
}

export default Index;
